<?php
namespace App;

use Workerman\Worker;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use \Workerman\Autoloader;

class workerGateway
{
    function __construct($action=null,$type=null)
    {
        global $argv;
        $argv[0] = 'chat';
        $argv[1] = $action;
        $argv[2] = $type ? '-d' : '' ;
        $this->start();
    }
    private function start()
    {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
        Worker::runAll();
    }
    
    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker';
        $worker->eventHandler    = \App\Events::class;
        $worker->registerAddress = '127.0.0.1:4141';
        //$worker->count           = 2;
        if (substr(PHP_VERSION, 0, 1) == '7') {
            /*
            只有php7才支持worker->reusePort
            可以让每个进程均衡的接收任务
            */
            $worker->reusePort = true;
        }
    }
    
    private function startGateWay()
    {
        // ssl
        // $pem = __DIR__ . "/Ssl/server.pem";
        // $key = __DIR__ . "/Ssl/server.key";
        // if ( ! is_file($pem) || ! is_file($key)) {
        //     die("ssl文件不存在");
        // }
        // $context = [
        //     'ssl' => array(
        //         // 请使用绝对路径
        //         'local_cert'                 => $pem, // 也可以是crt文件
        //         'local_pk'                   => $key,
        //         'verify_peer'                => false,
        //         //'allow_self_signed' => true, //如果是自签名证书需要开启此选项
        //     )
        // ];
        // $gateway = new Gateway("Websocket://0.0.0.0:7788", $context);

        $gateway = new Gateway("websocket://0.0.0.0:8282");
        $gateway->name                 = 'Gateway';
        $gateway->lanIp                = '127.0.0.1';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '';// {"type":"ping"}
        $gateway->registerAddress      = '127.0.0.1:4141';
        //$gateway->count                = 2;
    }
    
    private function startRegister()
    {
        new Register('text://0.0.0.0:4141');
    }
}